package com.mgr.controller;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mgr.dao.TransactionDao;
import com.mgr.service.AccountService;
import com.mgr.service.CustomerService;
import com.mgr.service.TransactionService;

@Controller
public class InternalTransferController3 {

	@Autowired
	private AccountService accountService;

	@Autowired
	private CustomerService customerService;


	@Autowired
	private TransactionDao transactionDao;
	@Autowired
	private TransactionService transactionService;

	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping("/internaltransfer2")
	public ModelAndView setFormTransferStep2(HttpSession session,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView(
				"internaltransaction3.tile");
		int accId2, amount;
		if (session.getAttribute("user") == null) {
			session.invalidate();
			modelAndView.setViewName("login");
		} else {
			try {
				accId2 = Integer.parseInt(request.getParameter("accId2"));
				amount = Integer.parseInt(request.getParameter("amount"));
				int accId1 = (Integer) session.getAttribute("accId1");
				if (!accountService.verifyBalance(accId1, amount)) {
					String messErrverifyBalance = rb.getString("invalidAmount");
					modelAndView.addObject("messErrverifyBalance",
							messErrverifyBalance);
					modelAndView.addObject("amount", request.getParameter("amount"));
					modelAndView.setViewName("internaltransaction2.tile");
				} else if (accountService.getAccount(accId2) == null) {

					String messErrAccoutNotExist = rb.getString("accoutnotexist");
					modelAndView.addObject("messErrAccoutNotExist",
							messErrAccoutNotExist);
					modelAndView.addObject("accId2", request.getParameter("accId2"));
					modelAndView.setViewName("internaltransaction2.tile");
				}else
				{
					session.setAttribute("accId2", accId2);
					session.setAttribute("amount", amount);
					modelAndView.addObject("accId2", accId2);
					modelAndView.addObject("amount", amount);
				}
			} catch (Exception e) {
				modelAndView.setViewName("internaltransaction2.tile");
				System.out.println("Error convert string to number");
			}
		}
		return modelAndView;
	}
}